package com.ffapp.demo.notice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.BusiTypeEmum;
import com.ffapp.demo.bean.FileTypeEmum;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.bean.UploadImgData;
import com.ffapp.demo.bean.UserSquadronListBean;
import com.ffapp.demo.bean.UserSquadronListData;
import com.ffapp.demo.bean.UserUploadFileListBean;
import com.ffapp.demo.common.AdapterFilesEdit;
import com.ffapp.demo.home.HomeIndexActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.LogUtil;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/***
 * 建筑信息-新增或编辑
 * **/
public class PublishActivity extends BasisActivity {

    boolean isEdit = true;
    AdapterFilesEdit mAdapterImg;
    @BindView(R.id.recyclerview_files)
    RecyclerView recyclerview_files;


    @BindView(R.id.edit_title)
    EditText edit_title;
    @BindView(R.id.edit_author)
    EditText edit_author;
    @BindView(R.id.edit_content)
    EditText edit_content;

    @BindView(R.id.text_push_receiver)
    TextView text_push_receiver;
    @BindView(R.id.text_if_top)
    TextView text_if_top;
    @BindView(R.id.img_switch)
    ImageView img_switch;

    UserSquadronListBean mListBeanSquadron;
    UserSquadronListData mParamsSquadron;

    boolean isTop = false;

    String[] recerverIds;


    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        setDefautTrans(false);
        super.initViews();
        setContentView(R.layout.notice_public_activity);
        setTitle("发布公告");
        setTitleLeftButton(null);

        recyclerview_files.setLayoutManager(new GridLayoutManager(mContext, 3));
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        mAdapterImg = new AdapterFilesEdit(mContext,null,6,REQUEST_PIC);
        recyclerview_files.setAdapter(mAdapterImg);
//            getSquadron(false);

        edit_author.setText(LoginBean.getInstance().getUserInfo().getName());
        ViewUtils.setEditTextEnable(false,edit_author);
        setReceiverViews();
        setTopView();
    }


    @OnClick(R.id.btn_post)
    void checkAndPost() {
        String title = edit_title.getText().toString().trim();
        String author = edit_author.getText().toString().trim();
        String content = edit_content.getText().toString().trim();

        if (TextUtils.isEmpty(title)) {
            showToast(edit_title.getHint() + "");
            return;
        }
//        if (TextUtils.isEmpty(content)) {
//            showToast(edit_content.getHint() + "");
//            return;
//        }
//        if (TextUtils.isEmpty(author)) {
//            showToast(edit_author.getHint() + "");
//            return;
//        }
        checkImgPost();
    }


//    private void getSquadron(boolean isPop) {
//        MyParams params = new MyParams();
//        if (isPop) {
//            showProgress();
//        }
//        params.put("showAll","1");
//        MyHttpUtils.post(Constants.URL_COMMENT_GET_SQUADRON, params, new MyHttpListener() {
//                    @Override
//                    public void onSuccess(int httpWhat, Object result) {
//                        mListBeanSquadron = (UserSquadronListBean) result;
//                        if (isPop) {
//                            onPushReceiverChooseClick();
//                        }
//                    }
//
//                    @Override
//                    public void onFinish(int httpWhat) {
//                        dismissProgress();
//                    }
//                },
//                0, UserSquadronListBean.class);
//
//    }

//    @OnClick({R.id.view_push_receiver_zone})
//    void onPushReceiverChooseClick() {
//        if (!isEdit) return;
//        if (mListBeanSquadron == null) {
//            getSquadron(true);
//            return;
//        }
//        //TODO
//        //选择推送对象
//    }

    @SuppressLint("StaticFieldLeak")
    private void checkImgPost() {
        if (!isEdit) return;
        showProgress();
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                UploadImgData data;
                for (int i = 0, l = mAdapterImg.mListBean.size(); i < l; i++) {
                    data = mAdapterImg.mListBean.get(i);
                    if (data.isNeedpost()) {
                        postImg(i, mAdapterImg.mListBean.get(i), BusiTypeEmum.通知公告附件.getName(), mAdapterImg);
                    }
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                LogUtil.i("onPostExecute--->");
                if(mAdapterImg.isNeedUpload()){
                    hideLoading();
                    DialogUtils.DialogOkMsg(mContext,"文件上传失败");
                }else {
                    postReal();
                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
        }.execute("");

    }

    private void postImg(int position_inlist, UploadImgData imgData, String busiType, AdapterFilesEdit adapter) {
//        String filepathTemp = Constants.DIR_TEMP + FileUtils.getFileNameByPath(imgData.getPath());
//        ImageUtils.savePicToSdcard(ImageUtils.getBitmapBySize(imgData.getPath(), 1000, 1000), Constants.DIR_TEMP, FileUtils.getFileNameByPath(imgData.getPath()));
        MyParams params = new MyParams();
        params.add("busiType", busiType);
        params.put("files", new File(imgData.getPath()));
        params.put("fileType", FileTypeEmum.Other);
//        params.put("fileType", FileTypeEmum.Image);
        params.put("dataOrder", "0");

        MyHttpUtils.postFileExcute(Constants.URL_USER_ATTACHMENT_UPLOAD, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                UserUploadFileListBean listBean = (UserUploadFileListBean) result;
                adapter.setImgId(position_inlist, listBean.getImgIdFirst());
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                super.onFailure(httpWhat, result);
            }

            @Override
            public void onFinish(int httpWhat) {
            }
        }, UserUploadFileListBean.class);

    }


    public final static int REQUEST_PIC = 12;
    public final static int REQUEST_RECEIVER_CHOOSE = 13;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != Activity.RESULT_OK)return;

        if (requestCode == REQUEST_PIC) {
            String path = null;
            List<String> list = data.getStringArrayListExtra("paths");
            path = list.get(0);
            LogUtil.i("path-getPathFromUri-->"+path);
            mAdapterImg.addFile(list);
        }else if(REQUEST_RECEIVER_CHOOSE == requestCode){
            recerverIds = data.getStringArrayExtra("data");
            setReceiverViews();
        }

    }
    
    void postReal(){

        String title = edit_title.getText().toString().trim();
        String author = edit_author.getText().toString().trim();
        String content = edit_content.getText().toString().trim();
        MyParams params = new MyParams();
        showProgress();
//        params.put("id", "");
        params.put("title", title);
        params.put("author", author);
        params.put("content", content);
        params.put("isTop", isTop?"1":"0");
        params.put("sync", "0");
        if(recerverIds == null || recerverIds.length == 0){
            params.put("receiveType", "1");//接收类型，接收类型，1：全员可查看，2：部门，3：分组，4：指定人
        }else {
            params.put("receiveType", "4");
            params.putObj("noticeIds", recerverIds);
        }
        if(mAdapterImg.mListBean != null && mAdapterImg.mListBean.size() > 0){

            params.putObj("fileIds",mAdapterImg.getParamsImgidArray());
        }
        showLoading();
        MyHttpUtils.post(Constants.URL_NOTICE_SAVE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        setResult(Activity.RESULT_OK);
                        EventBus.getDefault().post(new HomeIndexActivity.EventHomeIndex(HomeIndexActivity.EventHomeIndex.TYPE_NEWS_REFRESH));
                        DialogUtils.DialogOKmsgFinish(mContext,((BasisBean)result).getStatusInfo());
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        hideLoading();
                    }
                },
                0, BasisBean.class);
    }


    @OnClick(R.id.view_switch_zone)
    void onSwitchTopClick() {
        isTop = !isTop;
        setTopView();
    }

    void setTopView() {
        if (isTop) {
            text_if_top.setText("是");
            img_switch.setImageResource(R.drawable.btn_switch_on);
        } else {
            text_if_top.setText("否");
            img_switch.setImageResource(R.drawable.btn_switch_off);
        }
    }

    @OnClick(R.id.view_push_receiver_zone)
    void onReceiverChooseClick(){
        Bundle bundle = new Bundle();
        bundle.putSerializable("data",recerverIds);
        ActivityTool.skipActivityForResult(mContext,ReceiverChooseActivity.class,bundle,REQUEST_RECEIVER_CHOOSE);
    }

    void setReceiverViews(){
        if(recerverIds == null || recerverIds.length ==0){
            text_push_receiver.setText("全部");
        }else {
            text_push_receiver.setText("已选"+recerverIds.length+"位");
        }
    }

}
